import './App.less';
import { Switch, Route, Redirect, withRouter } from 'react-router-dom';
import { routes, flattenRoute, DynamicRoutes } from '@/router/index';
import { Suspense, useEffect } from 'react';
import { useContainer } from 'unstated-next';
import Local from '@/store';
import { GETSESSIONSTORE } from './utils/cookies';

function App(props) {
  // console.log('props', props);
  const {
    permissonStore: { permissionList, setPermissionList },
  } = useContainer(Local);
  // console.log('permissionList', permissionList);
  const {
    location: { pathname },
    history,
  } = props;
  const isLogin = GETSESSIONSTORE('useInfo') ? true : false;
  const flattenList = flattenRoute.map((item) => item.path);
  // console.log('flattenList', flattenList);
  useEffect(() => {
    // console.log('userInfo', userInfo);
    if (isLogin) {
      if (permissionList.length === 0) {
        setPermissionList(DynamicRoutes);
      }
      if (pathname == '/login') {
        return history.replace(DynamicRoutes[0].redirect || DynamicRoutes[0].path || '/login');
      }
      if (flattenList.indexOf(pathname) <= -1) {
        history.replace('/404');
      }
    } else {
      history.replace('/login');
    }
  }, [pathname]);

  return (
    <div className="App">
      <Switch>
        <Suspense fallback={<h1>...Loading</h1>}>
          {[...routes, ...permissionList].map((item) => {
            return <Route path={item.path} component={item.component} key={item.path} />;
          })}
          <Redirect from="/" exact to="/login" />
        </Suspense>
      </Switch>
    </div>
  );
}

export default withRouter(App);
